// // 引入express框架
// var express = require('express');
// // 创建路由对象
// var router = express.Router();
// let listModel = require('../db/projectlist');
// const { v4: uuidv4 } = require('uuid');

// /* GET home page. */
// // 首页路由，渲染index页面
// router.get('/', function (req, res, next) {
//     res.render('index', { title: 'Express' });
// });

// // 获取所有项目
// router.get('/list', function (req, res, next) {
//     listModel.find().then(function (data) {
//         // console.log('数据库数据', data);
//         res.json({ code: 200, data });
//     }).catch(err => {
//         res.json({ code: 500, msg: '获取失败', error: err.message });
//     });
// });

// // 新增项目
// router.post('/add', function (req, res, next) {
//     let list = req.body;
//     console.log('收到前端数据:', list); // 打印收到的数据
//     if (!list.id) list.id = uuidv4();
//     if (!list.projectNumber) list.projectNumber = 'P' + Date.now();
//     listModel.create(list).then(function (data) {
//         res.json({
//             code: 200,
//             data: data,
//             msg: '添加成功'
//         });
//     }).catch(err => {
//         console.error('写入数据库失败:', err); // 打印详细错误
//         res.json({
//             code: 500,
//             msg: '添加失败',
//             error: err.message
//         });
//     });
// });

// // 更新项目
// router.post('/update', function (req, res, next) {
//     let list = req.body;
//     listModel.updateOne({ id: list.id }, list).then(function (data) {
//         res.json({
//             code: 200,
//             data: data
//         });
//     });
// });

// // 删除项目
// router.post('/delete', function (req, res, next) {
//     let list = req.body;
//     if (!list.id) return res.json({ code: 400, msg: '缺少id' });
//     listModel.deleteOne({ id: list.id }).then(function (data) {
//         res.json({
//             code: 200,
//             data: data,
//             msg: '删除成功'
//         });
//     }).catch(err => {
//         res.json({
//             code: 500,
//             msg: '删除失败',
//             error: err.message
//         });
//     });
// });

// // 查询项目（支持多条件模糊搜索、时间范围、分页，空条件返回全部）
// router.post('/search', function (req, res, next) {
//     let {
//         projectNumber,
//         projectName,
//         manager,
//         status,
//         projectType,
//         contractNumber,
//         relatedCustomer,
//         projectCategory,
//         startTime,
//         endTime,
//         page = 1,
//         pageSize = 10
//     } = req.body;
//     const skip = (page - 1) * pageSize;
//     let query = {};

//     // 只添加有值的字段，空字符串不加入查询条件
//     if (projectNumber && projectNumber.trim() !== '') query.projectNumber = { $regex: projectNumber, $options: 'i' };
//     if (projectName && projectName.trim() !== '') query.projectName = { $regex: projectName, $options: 'i' };
//     if (manager && manager.trim() !== '') query.manager = { $regex: manager, $options: 'i' };
//     if (contractNumber && contractNumber.trim() !== '') query.contractNumber = { $regex: contractNumber, $options: 'i' };
//     if (relatedCustomer && relatedCustomer.trim() !== '') query.relatedCustomer = { $regex: relatedCustomer, $options: 'i' };
//     if (status && status.trim() !== '') query.status = status;
//     if (projectType && projectType.trim() !== '') query.projectType = projectType;
//     if (projectCategory && projectCategory.trim() !== '') query.projectCategory = projectCategory;

//     // 时间范围（可选，按startTime）
//     if (startTime && endTime) {
//         query.startTime = { $gte: startTime, $lte: endTime };
//     } else if (startTime) {
//         query.startTime = { $gte: startTime };
//     } else if (endTime) {
//         query.startTime = { $lte: endTime };
//     }

//     // 调试：打印最终查询条件
//     // console.log('最终查询条件:', query);

//     listModel.find(query)
//         .skip(skip)
//         .limit(parseInt(pageSize))
//         .sort({ createTime: -1 })
//         .then(function (data) {
//             listModel.countDocuments(query).then(function (total) {
//                 res.json({
//                     code: 200,
//                     data: data,
//                     total: total,
//                     page: parseInt(page),
//                     pageSize: parseInt(pageSize),
//                     msg: '查询成功'
//                 });
//             });
//         }).catch(err => {
//             res.json({
//                 code: 500,
//                 msg: '查询失败',
//                 error: err.message
//             });
//         });
// });

// // 导出路由对象
// module.exports = router;

const express = require('express');
const router = express.Router();
const Project = require('../db/project');
const { v4: uuidv4 } = require('uuid');

// 查询（分页+搜索）
router.post('/search', async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword, ...rest } = req.body;
    const skip = (page - 1) * pageSize;
    const query = {};
    
    // 处理各个字段的模糊搜索
    if (rest.projectNumber && rest.projectNumber.trim() !== '') {
      query.projectNumber = { $regex: rest.projectNumber.trim(), $options: 'i' };
    }
    if (rest.projectName && rest.projectName.trim() !== '') {
      query.projectName = { $regex: rest.projectName.trim(), $options: 'i' };
    }
    if (rest.relatedClient && rest.relatedClient.trim() !== '') {
      query.relatedClient = { $regex: rest.relatedClient.trim(), $options: 'i' };
    }
    if (rest.contractNumber && rest.contractNumber.trim() !== '') {
      query.contractNumber = { $regex: rest.contractNumber.trim(), $options: 'i' };
    }
    if (rest.signatory && rest.signatory.trim() !== '') {
      query.signatory = { $regex: rest.signatory.trim(), $options: 'i' };
    }
    if (rest.personInCharge && rest.personInCharge.trim() !== '') {
      query.personInCharge = { $regex: rest.personInCharge.trim(), $options: 'i' };
    }
    
    // 精确匹配字段
    if (rest.status && rest.status.trim() !== '') {
      query.status = rest.status.trim();
    }
    if (rest.projectType && rest.projectType.trim() !== '') {
      query.projectType = rest.projectType.trim();
    }
    if (rest.projectCategory && rest.projectCategory.trim() !== '') {
      query.projectCategory = { $regex: rest.projectCategory.trim(), $options: 'i' };
    }
    
    // 时间范围搜索
    if (rest.creationTime && rest.creationTime.length === 2) {
      const [startDate, endDate] = rest.creationTime;
      if (startDate && endDate) {
        query.creationTime = {
          $gte: new Date(startDate).toISOString(),
          $lte: new Date(endDate).toISOString()
        };
      }
    }
    
    // 关键词搜索（如果提供了keyword，则搜索多个字段）
    if (keyword && keyword.trim() !== '') {
      query.$or = [
        { projectName: { $regex: keyword.trim(), $options: 'i' } },
        { projectNumber: { $regex: keyword.trim(), $options: 'i' } },
        { relatedClient: { $regex: keyword.trim(), $options: 'i' } },
        { contractNumber: { $regex: keyword.trim(), $options: 'i' } },
        { signatory: { $regex: keyword.trim(), $options: 'i' } },
        { personInCharge: { $regex: keyword.trim(), $options: 'i' } }
      ];
    }
    
    console.log('搜索条件:', query);
    
    const total = await Project.countDocuments(query);
    const list = await Project.find(query).skip(skip).limit(Number(pageSize)).sort({ creationTime: -1, _id: -1 });
    
    res.json({ 
      code: 200, 
      data: { list, total },
      msg: '查询成功'
    });
  } catch (err) {
    console.error('搜索失败:', err);
    res.json({ code: 500, msg: '查询失败', error: err.message });
  }
});

// 新增
router.post('/add', async (req, res) => {
  try {
    const data = req.body;
    data.creationTime = new Date().toISOString();
    data.updateTime = data.creationTime;
    const doc = await Project.create(data);
    res.json({ code: 200, data: doc, msg: '添加成功' });
  } catch (err) {
    res.json({ code: 500, msg: '添加失败', error: err.message });
  }
});

// 修改
router.post('/update', async (req, res) => {
  try {
    const { id, ...updateData } = req.body;
    if (!id) return res.json({ code: 400, msg: '缺少id' });
    updateData.updateTime = new Date().toISOString();
    const doc = await Project.findOneAndUpdate({ _id: id }, updateData, { new: true });
    res.json({ code: 200, data: doc, msg: '修改成功' });
  } catch (err) {
    res.json({ code: 500, msg: '修改失败', error: err.message });
  }
});

// 删除
router.post('/delete', async (req, res) => {
  try {
    const { id } = req.body;
    if (!id) return res.json({ code: 400, msg: '缺少id' });
    await Project.deleteOne({ _id: id });
    res.json({ code: 200, msg: '删除成功' });
  } catch (err) {
    res.json({ code: 500, msg: '删除失败', error: err.message });
  }
});

module.exports = router;